
from .compBase import TBaseComp
from datetime import datetime , timedelta

class TCompIotCalculate(TBaseComp):
    def __init__(self):
        super().__init__()
        self.componentKey = 'iotCalculate'
        self.handlers={
            "9001": self.cal9001
        }
    def getUtcTimeStr(self , dt ):
        res=''
        try:
            res = (dt + timedelta(hours=-8)).strftime('%Y-%m-%dT%H:%M:%SZ')
        except Exception as er:
            print(er)
        return  res
    def getValues(self , devCode , varId , fromDt , endDt ):
        status = 0
        v0 = 0
        v1 = 0
        try:
            sql = f"select first(v) as v0 , last(v) as v1 from {devCode}  where vid='{varId}' and time>='{fromDt}' and time<='{endDt}' "
            tdbCompCode= self.settings['tdbCompCode']
            tdbCode = self.settings['tdbCode']
            if tdbCompCode in self.manager.components.keys():
                tdbComp = self.manager.components[tdbCompCode]
                res = tdbComp.queryPost(tdbCode , sql  )
                if res['status']==1 :
                    values = res['result'][0]['series'][0]['values'][0]
                    v0 = values[1]
                    v1 = values[2]
                    status = 1
                    print(res['result'])
        except Exception as er:
            print(er)
        return  status , v0 ,v1

    '''
    无锡电站 电量计算
    '''
    def cal9001_(self ):
        res={
            "s":0 ,
            "y": 0,
            "m":0,
            "d":0
        }
        try:
            endDt = datetime.now()
            endDtStr = self.getUtcTimeStr(endDt)
            fromDtYear = datetime( endDt.year , 1 ,1 )
            fromDtMonth = datetime( endDt.year , endDt.month ,1 )
            fromDtDay = datetime( endDt.year , endDt.month ,endDt.day )
            vInit = 14204

            initFlag = endDt.year==2025 and endDt.month == 1

            #year
            sy , v10 , v11 = self.getValues('wxHw01', 722 , self.getUtcTimeStr(fromDtYear ), endDtStr)
            sy , v20 , v21 = self.getValues('wxHw02', 901 , self.getUtcTimeStr(fromDtYear ), endDtStr)
            sy , v30 , v31 = self.getValues('wxHw03', 1080 , self.getUtcTimeStr(fromDtYear ), endDtStr)
            v0  = vInit if initFlag else (v10+v20+v30)
            vy = v11 + v21 + v31 - vInit

            #month
            sm, v10, v11 = self.getValues('wxHw01', 722, self.getUtcTimeStr(fromDtMonth), endDtStr)
            sm, v20, v21 = self.getValues('wxHw02', 901, self.getUtcTimeStr(fromDtMonth), endDtStr)
            sm, v30, v31 = self.getValues('wxHw03', 1080, self.getUtcTimeStr(fromDtMonth), endDtStr)
            v0  = vInit if initFlag else (v10+v20+v30)
            vm = v11 + v21 + v31 - v0

            #day
            sd, v10, v11 = self.getValues('wxHw01', 722, self.getUtcTimeStr(fromDtDay), endDtStr)
            sd, v20, v21 = self.getValues('wxHw02', 901, self.getUtcTimeStr(fromDtDay), endDtStr)
            sd, v30, v31 = self.getValues('wxHw03', 1080, self.getUtcTimeStr(fromDtDay), endDtStr)
            vd = v11 + v21 + v31 - v10 - v20 - v30

            res={
                "s": 1 if (sy==1 and sm==1 and sd==1) else 0,
                "y": vy,
                "m":vm,
                "d":vd
            }
        except Exception as er:
            print(er)
        return  res
    def cal9001(self ):
        res= self.cal90001_getValue(datetime.now())
        return res
    def cal90001_getValue(self , dt):
        res={
            "s":0 ,
            "y": 0,
            "m":0,
            "d":0
        }
        try:
            utcDt = self.getUtcTimeStr(dt)
            sql = f"select last(v) from wx64501 where vid='567' and time<='{utcDt}' order by time "
            tdbCode = self.settings['tdbCode']
            tdb = self.manager.components['influx']
            result = tdb.queryPost(tdbCode , sql  )
            lastValue = result['result'][0]['series'][0]['values'][0][1]

            dtYear = self.getUtcTimeStr(datetime(dt.year ,1 , 1 ))
            dtMonth = self.getUtcTimeStr(datetime(dt.year ,dt.month , 1 ))
            dtDay = self.getUtcTimeStr(datetime(dt.year ,dt.month ,  dt.day))
            sqlYear = f"select first(v) from wx64501 where vid='567' and time>='{dtYear}' order by time "
            result = tdb.queryPost(tdbCode , sqlYear  )
            yearValue = result['result'][0]['series'][0]['values'][0][1]
            sqlmonth = f"select first(v) from wx64501 where vid='567' and time>='{dtMonth}' order by time "
            result = tdb.queryPost(tdbCode , sqlmonth  )
            monthValue = result['result'][0]['series'][0]['values'][0][1]
            sqlDay = f"select last(v) from wx64501 where vid='567' and time<='{dtDay}' order by time "
            result = tdb.queryPost(tdbCode , sqlDay  )
            dayValue = result['result'][0]['series'][0]['values'][0][1]

            res["y"] = int(lastValue - yearValue)
            res["m"] = int(lastValue - monthValue)
            res["d"] = int(lastValue - dayValue)
            res["s"] = 1

        except Exception as er:
            print(er)
        return  res
compIotCalculate = TCompIotCalculate()
compIotCalculate.regist()
